package com.haierCamera.customapplication.ui.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.vo.ConfigDeviceResponse;
import com.haierCamera.customapplication.databinding.HzklActivityAddStep3Binding;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.StringUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import dagger.Lazy;

public class HZKLCameraDeviceAddStepThreeActivity extends BaseActivity {

    HzklActivityAddStep3Binding binding;

    @Inject
    ApiService apiService;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_add_step_3);

        initImage();
        binding.imgReturn.setOnClickListener((v)->{
            finish();
        });

        binding.cbAlreadySeen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    binding.btnNext.setBackgroundDrawable(getResources().getDrawable(R.drawable.hzkl_btn_blue));
                    binding.btnNext.setClickable(true);
                } else {
                    binding.btnNext.setBackgroundDrawable(getResources().getDrawable(R.drawable.hzkl_btn_grey));
                    binding.btnNext.setClickable(false);
                }
            }
        });

        binding.tvContent2.setOnClickListener((v)->{
            startActivity(new Intent(this,HZKLNotifyGreenLightActivity.class)
                    .putExtra("dt",getIntent().getStringExtra("dt")));
        });

        binding.btnNext.setOnClickListener((v)->{

                List<String> split= Arrays.asList(SharedPreferencesUtils.getString("dt","").split(","));

                boolean isGoSoft = false;
                for (int i = 0; i < split.size(); i++) {
                    if (getIntent().getStringExtra("dt")!=null && !getIntent().getStringExtra("dt").equals("") &&
                            getIntent().getStringExtra("dt").equals(split.get(i)) ) {
                        isGoSoft = true;
                    }
                }
                if (isGoSoft) {
                    startActivity(new Intent(HZKLCameraDeviceAddStepThreeActivity.this,HZKLSoftAPAddActivity.class)
                            .putExtra("sn",getIntent().getStringExtra("sn"))
                            .putExtra("sc",getIntent().getStringExtra("sc"))
                            .putExtra("dt",getIntent().getStringExtra("dt"))
                            .putExtra("ssid",getIntent().getStringExtra("ssid"))
                            .putExtra("ssidPwd",getIntent().getStringExtra("ssidPwd")));

                } else {
                    requestStoragePermission();
                }

        });


        configDevice();

    }

    private void initImage(){
        if (getIntent().getStringExtra("dt").contains("TF1D")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tf1d_light);
        } else if (getIntent().getStringExtra("dt").contains("TE3")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_te3_light);
        } else if (getIntent().getStringExtra("dt").contains("TF1T")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tf1t_light);
        } else if (getIntent().getStringExtra("dt").contains("TP7S")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tp7se_light);
        } else if (getIntent().getStringExtra("dt").contains("TP2E")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tp2e_light);
        } else if (getIntent().getStringExtra("dt").contains("TC2E")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tc2e_light);
        } else if (getIntent().getStringExtra("dt").contains("TF3")) {
            binding.ivImg.setImageResource(R.drawable.hzkl_tf3_light);
        } else {
            binding.ivImg.setImageResource(R.drawable.hzkl_tp2e_light);
        }
    }

    private void configDevice() {
        ResourceConvertUtils.convertToResource(apiService.configDevice())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            errorProcessLazy.get().process(resource);
                            break;
                        case SUCCESS:
                            List<ConfigDeviceResponse.item> list =  resource.data;
                            List<String> list_s = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                list_s.add(list.get(i).value);
                            }
                            SharedPreferencesUtils.saveString("dt", StringUtils.listToString1(list_s));

                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void requestStoragePermission(){
        boolean isMinSDKM = Build.VERSION.SDK_INT < 23;
        boolean isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        if (isMinSDKM || isGranted) {
//            checkOnBindAndRemind();\
            startNormalAddActivity();
            // 存储权限
            return;
        }
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            Log.d("Uriah", "Uriah + shouldShowRequestPermission true");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
        }

    }

    private void startNormalAddActivity() {
        startActivity(new Intent(HZKLCameraDeviceAddStepThreeActivity.this,CameraDeviceAddActivity.class)
                .putExtra("sn",getIntent().getStringExtra("sn"))
                .putExtra("sc",getIntent().getStringExtra("sc"))
                .putExtra("dt",getIntent().getStringExtra("dt"))
                .putExtra("ssid",getIntent().getStringExtra("ssid"))
                .putExtra("ssidPwd",getIntent().getStringExtra("ssidPwd")));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // TODO Auto-generated method stub
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if(requestCode == 3){
//                checkOnBindAndRemind();
                startNormalAddActivity();
            }

        } else {
            if(requestCode == 3){
                toast(getString(R.string.HZKLtoast_permission_storage_forbidden));
            }

        }

    }


}
